package org.example.myleet.p567;

public class Solution1 {
    /**
     * 6 ms
     * 官方解法，利用diff记录窗口与s1比较的变化
     */
    public boolean checkInclusion(String s1, String s2) {
        if (s1.length() > s2.length()) {
            return false;
        }
        int winLen = s1.length(), len2 = s2.length(), diff = 0;
        int[] freq1 = new int[26];
        int[] freq2 = new int[26];
        for (int i=0; i<winLen; i++) {
            int c1 = s1.charAt(i)-'a';
            ++freq1[c1];
            int c2 = s2.charAt(i)-'a';
            ++freq2[c2];
        }
        for (int i=0; i<26; i++) {
            //初始化diff
            if (freq1[i] != freq2[i]) {
                ++diff;
            }
        }
        for (int i=winLen; i<len2; i++) {
            if (0 == diff) {
                return true;
            }
            //进入窗口的字符
            int cout = s2.charAt(i-winLen)-'a';
            //离开窗口的字符
            int cin = s2.charAt(i)-'a';
            if (cout == cin) {
                //对窗口内字符频率实际没有影响
                continue;
            }
            if (freq2[cout] == freq1[cout]) {
                //字符离开窗口前频率相等，离开后频率就不想等了，所以++diff
                ++diff;
            }
            --freq2[cout];
            if (freq2[cout] == freq1[cout]) {
                //字符离开窗口后频率相等，差异减少了，所以--diff
                --diff;
            }
            if (freq2[cin] == freq1[cin]) {
                //字符进入窗口前频率相等，离开后频率就不想等了，所以++diff
                ++diff;
            }
            ++freq2[cin];
            if (freq2[cin] == freq1[cin]) {
                //字符进入窗口后频率相等，差异减少了，所以--diff
                --diff;
            }
        }
        if (0 == diff) {
            //最后还要观察最后一次滑窗的结果
            return true;
        }
        return false;
    }
}
